import MD5 from "./md5.js" ;
var myHost = process.env.NODE_ENV === 'developments' ? 'http://192.168.0.6' :  "https://brain.joiny.cn"  ;
// #ifdef H5
myHost = 'http://192.168.0.6' ;
// #endif
function signData(data){
   return MD5.md5(data.timestamp + "7ff4f5d3c161e2cfdeb91466792dc489");
}

function get(serviceName, data, success, error) {
	doRequest(serviceName, data, success, error , 'GET'); 
}

function post(serviceName, data, success, error) {
	doRequest(serviceName, data, success, error , 'POST');
}

function doRequest(serviceName, data, success, error , method){
	// // #ifdef MP-WEIXIN
	// if(data['js_code']){
	// 	reqesut(serviceName, data, success, error , method);
	// 	return ;
	// }
	// wx.login({
	// 	success:function(result) {
	// 		data['js_code'] = result.code ;
	// 		reqesut(serviceName, data, success, error , method);
	// 	}
	// });
	// return ;
	// // #endif
	reqesut(serviceName, data, success, error , method);
}

function reqesut(serviceName, data, success, error , method){ 
	if(serviceName.indexOf("?") > -1){
		var arr = serviceName.split("?") ;
		var paramArr = arr[1].split("&");
		for (var i = 0; i < paramArr.length; i++) {
			var cur = paramArr[i] ;
			var curArr = cur.split("=") ;
			data[curArr[0]] = curArr[1] ;
		}
		serviceName = arr[0] ;
	}
	var jsonData = {};
	for(var key in data){
		if ( data[key] != "null" && ( !!data[key] || data[key] == false || data[key] == 0) ) {
			jsonData[key] = data[key] ;
		}else{
			jsonData[key] = "" ;
		}
	}
	var token = uni.getStorageSync("token");
	jsonData['timestamp'] = new Date().getTime() ;
	jsonData['sign'] = signData(jsonData);
	uni.request({
		url: myHost + serviceName ,
		method: method ,
		data: jsonData ,
		header:{
			token : token
		},
		success: res => {
			var data = res.data ;
			uni.stopPullDownRefresh();
			if (data.state == "needLogin") {
				uni.removeStorageSync("token");
				uni.navigateTo({
					url: "/pages/login/login"
				});
				return ;
			}
			if(data.state == "openShop" ){
				uni.redirectTo({
					url:"/pages/modifyShopInfo/modifyShopInfo"
				});
				return ;
			}
			if(data.state == "ok" || !data.state ){
				success(data) ;
				return ;
			}
			if (typeof error == 'function') {
				error(data) ;
			}else{
				showTips(data.err);
			}
		},
		fail: () => {
			uni.showToast({
				title: '服务不可用',
				icon : 'none'
			});
			uni.hideLoading();
			uni.stopPullDownRefresh();
		},
		complete: () => {
			
		}
	});
}

function showTips(tip){
	if(tip && tip.length > 10){
		uni.showModal({
			title:'提示',
			content: tip ,
			showCancel:false,
			confirmColor:'#009688'
		});
	}else{
		uni.showToast({
			title: tip ,
			icon : 'none',
			duration:3000
			
		});
	}
}


//时间戳格式化为日期
function formatDate(timestamp) {
	var now = new Date(parseFloat(timestamp));
	var year = now.getFullYear();
	var month = formatMinNum(now.getMonth() + 1);
	var date = formatMinNum(now.getDate());
	var hour = formatMinNum(now.getHours());
	var minute = formatMinNum(now.getMinutes());
	var second = formatMinNum(now.getSeconds());
	return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

//日期格式化为年月日
function formatDays(date) {
	var now =  date || new Date();
	var year = now.getFullYear();
	var month = formatMinNum(now.getMonth() + 1);
	var date = formatMinNum(now.getDate());
	var hour = formatMinNum(now.getHours());
	var minute = formatMinNum(now.getMinutes());
	var second = formatMinNum(now.getSeconds());
	return year + "-" + month + "-" + date ;
}

function formatMinNum(num){
	return num > 9 ? num : "0" + num ;
}

//格式化数字
function formatNum(num){
	if (num < 100000) {
		return (num+"").replace( /\B(?=(?:\d{3})+$)/g, ',' );
	}
	var wanNum = parseFloat(num/10000).toFixed(2);
	if (wanNum < 1000) {
		var str = wanNum + "" ;
		var intSum = str.substring(0,str.indexOf(".")).replace( /\B(?=(?:\d{3})+$)/g, ',' );//取到整数部分
		var dot = str.substring(str.length,str.indexOf(".")) ;//取到小数部分搜索
		return (wanNum+"").replace( /\B(?=(?:\d{3})+$)/g, ',' ) + '万';
	}
	wanNum = parseInt(num/10000) ;
	return (wanNum+"").replace( /\B(?=(?:\d{3})+$)/g, ',' ) + "万";
} 

//json转参数
function toParams(jsonData , filterKeys){
	var params = [] ;
	for(var key in jsonData){
		if (!!filterKeys && filterKeys.indexOf(key) > -1) {
			continue ;
		}
		var value = jsonData[key] ;
		value = value == 'null' || value == null ? '' : value ;
		params.push(key + "=" + value);
	}
	return params.join('&');
}

//返回历史页面
function goBack( defaultPage , title){
	var index = 1 ;
	var pageList = getCurrentPages();
	if (pageList.length <= index) {
		defaultPage = defaultPage || '/pages/home/home' ;
		defaultPage = defaultPage && defaultPage.indexOf("/pages/") == -1 ? "/pages/" + defaultPage + "/" + defaultPage : defaultPage ;
		uni.navigateTo({
			url: defaultPage 
		});
	}else{
		uni.navigateBack({
			delta: 1
		});
	}
	
	if (title) {
		setTimeout(e => {
			uni.showToast({
				title: title ,
				icon : 'success'
			});
		},200);
	}
}

function getCurPage(){
    var pages = getCurrentPages();
    return pages[pages.length-1];
}

function getPageRoute(e){
	/*获取当前路由*/
	let curPage = getCurPage();
	var route = "/" + curPage.route ;
	//在微信小程序或是app中，通过curPage.options；如果是H5，则需要curPage.$route.query（H5中的curPage.options为undefined）
	let curParam = curPage.options || curPage.$route.query;
	var params = toParams(curParam) ;
	return params ? route + "?" + params : route ;
}

function preview(url , urls){
	uni.previewImage({
		urls: urls ? urls : [url],
		current: url
	});
}

function goSuccessBack(title){
	goBack("",title);
}

function setDefault({ data , keys , defaultText = '--' }){
	if (!keys) {
		return ;
	}
	var keyArr = keys.split(',');
	for (var i = 0; i < keyArr.length; i++) {
		var key = keyArr[i] ;
		if (!data[key]) {
			data[key] = defaultText ;
		}
	}
	return data ;
}

export default {
	setDefault,
	reqesut,
	showTips,
	get,
	post,
	formatDate ,
	formatDays ,
	toParams ,
	formatNum ,
	goBack ,
	goSuccessBack ,
	myHost ,
	preview ,
	getPageRoute 
}
